/**
 * 
 */
package com.lorizz.picpub.task.impl;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import com.lorizz.picpub.task.TaskExecutor;
import com.lorizz.upm.Task;
import com.lorizz.upm.repository.Repository;

/**
 * @author wind hong
 *
 */
public class TaskIdExecutor implements TaskExecutor<Long> {
    
    private Log log = LogFactory.getLog(getClass());
    private Map<String, TaskExecutor<Task>> executors;
    private Repository upmRepository;

    public void setExecutors(Map<String, TaskExecutor<Task>> executors) {
        this.executors = executors;
    }

    public void setUpmRepository(Repository upmRepository) {
        this.upmRepository = upmRepository;
    }

    @Override
    @Transactional
    public boolean execute(Long taskId) {
        Task task = upmRepository.loadTask(taskId);
        if (task == null) {
            log.error(String.format("Task<%d> not found.", taskId));
            return false;
        }
        TaskExecutor<Task> executor = executors.get(task.getName());
        if (executor == null) {
            log.error(String.format("Task<%d> Executor<%s> not found", taskId, task.getName()));
            return false;
        }
        return executor.execute(task);
    }

}
